const GitOpenApi = require('../utils/gitOpenApi');
const AccessToken = require('../model/accessTokenModel');

async function insertOrUpdate(data) {
    const _data = {
        accessToken: data.access_token,
        refreshToken: data.refresh_token,
        createdAt: data.created_at,
        expiresIn: data.expires_in,
        userCode: data.userCode
    }
    const findItem = await AccessToken.findOne({where: {userCode: data.userCode} });
    if(findItem) {
        return AccessToken.update(_data, {where: {userCode: data.userCode} });
    }
    return AccessToken.create({..._data});
}

module.exports = {
    oauth(code, userCode) {
        const gitApi = new GitOpenApi();
        return gitApi.fetchAccessToken(code).then(async (data) => {
            return insertOrUpdate({...data, userCode})
        })
    },
    async getAccessToken() {
        const userCode = '123456';
        const tokenDao = await AccessToken.findOne({where: {userCode} });
        const gitApi = new GitOpenApi();
        const expiresTime = (parseInt(tokenDao.createdAt) + parseInt(tokenDao.expiresIn)) * 1000;
        if(!tokenDao) throw new Error('未进行oauth2授权，请先授权！');
        if(expiresTime <= Date.now()) {
            return gitApi.refreshAccessToken(tokenDao.refreshToken).then((data) => {
                return insertOrUpdate({...data, userCode}).then((item) => {
                    return item.accessToken;
                });
            })
        } else {
            return tokenDao.accessToken;
        }
    }
}
